﻿//--------------------------------------------------------------------------------------------------------------
// <copyright file="CSPMembershipRequestWUC.cs" company="Microsoft Corporation" date="01/01/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;


namespace CSP.WebParts.UserControls
{

    /// <summary>
    /// Shows the form to membership request submit
    /// </summary>  
    public class CSPMembershipRequestWUC : CSPBaseWUC
    {      

        #region Members
        protected RegularExpressionValidator RegularExpressionValidator1;
        protected RegularExpressionValidator RegularExpressionValidator2;
        protected HyperLink redirectLink;        
        protected TextBox tbUsername;
        protected TextBox tbPassword1;
        protected TextBox tbPassword2;
        protected TextBox tbFirstName;
        protected TextBox tbLastName;
        protected TextBox tbEmail;
        protected TextBox tbAddress;
        protected TextBox tbCity;
        protected TextBox tbPostalCode;
        protected TextBox tbPhone;
        protected TextBox tbChildren;
        protected TextBox tbElderlyRelatives;       
        protected Button RegisterSubmit;
        protected Panel pnlForm;
        protected Panel pnlResult;
        protected Label lblErrorUsername;
        protected Label RegisterChildren;
        protected Label RegisterElderlyRelatives;
        protected Label RegisterPostalCode;
       
        #endregion

        #region properties
        public string NoImageUrl { get; set; }
        public string CitizenImagesGalleryURL { get; set; }
        #endregion


        #region PageEvents
        /// <summary>
        /// Fired on page load
        /// </summary>  
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {                    
                        this.LoadLabels();                    
                });
            }          
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestLoadErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }

        /// <summary>
        /// Fired on page create child controls
        /// </summary>  
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                AddHipControls();

                RegisterSubmit.CausesValidation = true;
                RegisterSubmit.ValidationGroup = this.ID;
                RegisterSubmit.Click += new EventHandler(RegisterSubmit_Click);

                RegularExpressionValidator1.ErrorMessage = this.LoadResource(WebPartConstants.CSPUsernameValidatorMessage);
                RegularExpressionValidator2.ErrorMessage = this.LoadResource(WebPartConstants.CSPPasswordValidatorMessage);
          
            }            
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipRequestCreateChildControlsErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }
        #endregion


        #region Methods
        /// <summary>
        /// Gets the value of the labels
        /// </summary>
        protected void LoadLabels()
        {
            try
            {
                base.LoadLabels(this.pnlForm);
            }
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPGenericErrorMessage), this.GetType().Name, ex);
                throw ex;
            }       
        }
        #endregion
       

        #region ControlEvents
        /// <summary>
        /// Fired on submit button click
        /// </summary>
        protected void RegisterSubmit_Click(object sender, EventArgs e)
        {

           
                if (Page.IsValid)
                {
                    CSP.MembershipInterface.MembershipServiceClient client = null;
                    try
                    {
                        client = new CSP.MembershipInterface.MembershipServiceClient();
                        string username = Context.User.Identity.Name;

                        //** Checks if username is used by other citizen
                        CSP.MembershipInterface.ObjectModel.Citizen citizen = client.GetCitizenByUsername(this.tbUsername.Text);
                        if (citizen != null)
                        {
                            this.LogMessage(LoadResource(WebPartConstants.CSPErrorUsedUsername), this.GetType().Name);
                            WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPErrorUsedUsername));                 
                        }
                        //** end

                        CSP.MembershipInterface.ObjectModel.CitizenRequest citizenRequest = new CSP.MembershipInterface.ObjectModel.CitizenRequest();



                        citizenRequest.Username = this.tbUsername.Text;
                        citizenRequest.RequestType = CSP.MembershipInterface.ObjectModel.CitizenRequestType.Add;
                        citizenRequest.FirstName = this.tbFirstName.Text;
                        citizenRequest.LastName = this.tbLastName.Text;
                        citizenRequest.Password = this.tbPassword1.Text;                                                                        
                        citizenRequest.DisplayName = this.tbFirstName.Text + " " + this.tbLastName.Text;
                        citizenRequest.EmailAddress = this.tbEmail.Text;
                        citizenRequest.DefaultGroup = WebPartConstants.CSPCitizensDefaultGroup;
                        citizenRequest.Address = this.tbAddress.Text;
                        citizenRequest.City = this.tbCity.Text;
                        citizenRequest.PostalCode = this.tbPostalCode.Text;
                        citizenRequest.Phone = this.tbPhone.Text;
                        citizenRequest.Children = this.tbChildren.Text;
                        citizenRequest.ElderlyRelatives = this.tbElderlyRelatives.Text;


                        if (!Core.FormValidator.IsEmail(this.tbEmail.Text))
                        {
                            this.LogMessage(LoadResource(WebPartConstants.CSPErrorInvalidEmailFormat), this.GetType().Name);
                            WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPErrorInvalidEmailFormat));
                        }
                        if (!Core.FormValidator.IsNumber(this.tbChildren.Text))
                        {
                            this.LogMessage(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.RegisterChildren.Text)), this.GetType().Name);
                            WrapperWebPart.AddError(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.RegisterChildren.Text)));
                        }                       
                        if (!Core.FormValidator.IsNumber(this.tbElderlyRelatives.Text))
                        {
                            this.LogMessage(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.RegisterElderlyRelatives.Text)), this.GetType().Name);
                            WrapperWebPart.AddError(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber),LoadLabelName(this.RegisterElderlyRelatives.Text)));
                        }
                      



                        if (!WrapperWebPart.AnyError())
                        {
                            client.AddCitizenRequest(citizenRequest);
                            this.LogMessage(LoadResource(WebPartConstants.CSPRegisterSuccessMessage), this.GetType().Name);
                            WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPRegisterSuccessMessage));
                        }
                        else {
                            WrapperWebPart.AddError(string.Format(LoadResource(WebPartConstants.CSPBack)));                                        
                        }
                        
                    }
                    catch (CSP.Core.CSPException cspex)
                    {
                        throw cspex;
                    }
                    catch (Exception ex)
                    {
                        this.LogMessage(this.LoadResource(WebPartConstants.CSPCitizenProfileLoadErrorMessage), this.GetType().Name, ex);
                        throw ex;
                    }
                    finally
                    {
                        if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                            client.Close();
                    }                
            }
        }

        private string LoadLabelName(string lbl) {
            
            return lbl.Replace(":", ""); ;
        }
        #endregion
    }
}
